package com.liwei.weixin;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by Liwei on 2015/11/7.
 */
@ControllerAdvice
public class HandlerException {


    private static Logger logger = Logger.getLogger(HandlerException.class);

    /**
     * 只处理控制器抛出的异常
     * @param ex
     */
    @ExceptionHandler(Exception.class)
    public void handleException(Exception ex) {
        logger.debug("抛出了运行时刻异常，被 SpringMVC 捕获。。。");

        // 将系统抛出的异常堆栈信息输出到 log4j 组件
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if(sw!=null){
                try {
                    sw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pw!=null){
                pw.close();
            }
        }
        // 这一句是非常关键的
        logger.error(sw.toString());
    }

}
